package com.kl.forum.task;

import com.kl.forum.dao.*;
import com.kl.forum.entity.*;
import com.kl.forum.service.PushService;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.scheduling.annotation.Scheduled;
import org.springframework.stereotype.Component;

import java.util.*;

import static com.kl.forum.util.DateUtil.*;

@Component
public class PunchClockMatchTask {

    private Logger logger = LoggerFactory.getLogger(getClass());
    @Autowired
    private PunchMatchConfigMapper punchMatchConfigMapper;
    @Autowired
    private PunchMatchRecordMapper punchMatchRecordMapper;
    @Autowired
    private PunchMatchSignMapper punchMatchSignMapper;
    @Autowired
    private MemberMapper memberMapper;
    @Autowired
    private OperationRecordMapper operationRecordMapper;
    @Autowired
    private PushService pushService;
    @Autowired
    private PunchMatchNoticeMapper punchMatchNoticeMapper;

    @Scheduled(cron = "0 0 8 ? * *")
    public void punchClockMatchTask() {
        System.out.println("开始结算");
        logger.info("开始结算");
        Calendar c = Calendar.getInstance();
        c.set(Calendar.HOUR_OF_DAY, 8);
        c.set(Calendar.MINUTE, 00);
        c.set(Calendar.SECOND, 00);
        Date date=c.getTime();
        try {
            PunchMatchConfig config_1= punchMatchConfigMapper.selectByPrimaryKey(1);
            PunchMatchConfig config_3= punchMatchConfigMapper.selectByPrimaryKey(2);
            List<PunchMatchRecord> list=punchMatchRecordMapper.findPunchMatch();
            if (list!=null&&list.size()>0){
                for (int i=0;i<list.size();i++){
                    if (differentDays(list.get(i).getEndTime(),new Date())==0){
                        System.out.println("批量更新开始啦");
                        PunchMatchConfig config= punchMatchConfigMapper.selectByPrimaryKey(list.get(i).getConfigId());
                        //统计完成的人
                        int count =punchMatchSignMapper.findMatchSignCountWin(list.get(i).getId(),1);
                        int goldSum=list.get(i).getGoldNum();
                        if (count!=0){
                            double getGold=Math.floor(goldSum/count);
                            int getGolds=(int)getGold;
                            //参与成功
                            List<PunchMatchSign> punchMatchSignList=punchMatchSignMapper.findMatchSignByMatchId(list.get(i).getId(),1);
                            List<Member> memberList=memberMapper.findUserPunMatch(punchMatchSignList);
                            for (Member member:memberList){
                                //增加金币
                                member.setCoinNumber(member.getCoinNumber()+getGolds);
                                member.setAccumulativeCoin(member.getAccumulativeCoin()+getGolds);
                            }
                                memberMapper.updateByList(memberList);
                            for (Member member:memberList){
                                //批量增加到记录收益表
                                member.setType(6);
                                member.setNumber("+"+getGolds+"金币");
                                member.setName("晨起打卡");
                                member.setStatus(2);
                                member.setTransactionTime(new Date());
                                member.setReflectType(10);
                                member.setUserId(member.getcId());
                                member.setCreateTime(formatDateToString(new Date(),"yyyy-MM-dd HH:mm:ss"));
                            }
                            operationRecordMapper.insertByBatch(memberList);
                            //关闭报名表
                            for (PunchMatchSign punchMatchSign :punchMatchSignList){
                                punchMatchSign.setGetGoldNum(getGolds);
                                punchMatchSign.setIsDel(Byte.parseByte("0"));
                            }
                            if (punchMatchSignList!=null&&punchMatchSignList.size()>0){
                                punchMatchSignMapper.updateByBatch(punchMatchSignList);
                            }

                        }
                        //参与挑战的状态
                        List<PunchMatchSign> punchMatchSignList1=punchMatchSignMapper.findMatchSignByMatchId(list.get(i).getId(),2);
                        //更新报表的 参与挑战状态
                        for (PunchMatchSign punchMatchSign :punchMatchSignList1){
                            punchMatchSign.setIsDel(Byte.parseByte("0"));
                            punchMatchSign.setStatus(0);
                        }
                        if (punchMatchSignList1!=null&&punchMatchSignList1.size()>0){
                            punchMatchSignMapper.updateByBatch(punchMatchSignList1);

                        }
                        //关闭赛事表
                        list.get(i).setIsDel(Byte.parseByte("0"));
                        punchMatchRecordMapper.updateByPrimaryKeySelective(list.get(i));
                        //创建赛事表
                        PunchMatchRecord punchMatchRecord=new PunchMatchRecord();
                        punchMatchRecord.setConfigId(config.getId());
                        punchMatchRecord.setEndTime(addDays(date,config.getDayNum()));
                        insert(punchMatchRecord,date);
                        System.out.println("批量更新结束啦");
                    }
                }
            }else {
                //创建赛事表
                PunchMatchRecord record1=new PunchMatchRecord();
                record1.setEndTime(addDays(date,config_1.getDayNum()));
                record1.setConfigId(config_1.getId());
                insert(record1,date);
                PunchMatchRecord record=new PunchMatchRecord();
                record.setEndTime(addDays(date,config_3.getDayNum()));
                record.setConfigId(config_3.getId());
                insert(record,date);
            }
            List<PunchMatchNotice> noticeList= punchMatchNoticeMapper.findMatchNoticeListByIsDel(1);
            Collection<String> collection=new ArrayList<>();
            if (list!=null&&list.size()>0) {
                list= removeDuplicate1(list);
                for (int j=0;j<list.size();j++){
                    if (differentDays(list.get(j).getEndTime(),new Date())==0){
                        for(int i=0;i<noticeList.size();i++){
                            int matchId1=list.get(j).getId();
                            int matchId2=noticeList.get(i).getMatchId();
                            if (matchId1==matchId2){
                            collection.add(String.valueOf(noticeList.get(i).getUserId()));
                            noticeList.get(i).setIsDel(0);
                            }
                        }
                        if (collection.size()!=0){
                            pushService.pushMatchMessage(collection);
                            punchMatchNoticeMapper.updateBatch(noticeList);
                        }
                    }

                }
            }
            logger.info("赛事结算成功");
        }catch (Exception e){
            e.printStackTrace();
        }


    }
    public int  insert(PunchMatchRecord record,Date date ){
        record.setIsDel(Byte.parseByte("1"));
        record.setNumber(0);
        record.setGoldNum(0);
        record.setStartTime(date);
        record.setCreateTime(date);
       return punchMatchRecordMapper.insertSelective(record);
    }


    /**
     * 循环剔除重复元素
     * @param list
     */
    public static List<PunchMatchRecord> removeDuplicate1(List<PunchMatchRecord> list) {
        for (int i = 0; i < list.size() - 1; i++) { // i从第一个开始遍历
            for (int j = list.size() - 1; j > i; j--) { // j从最后一个开始遍历
                if (differentDays(list.get(j).getEndTime(),list.get(i).getEndTime())==0) {
                    list.remove(j);
                }
            }
        }
       return  list;
    }

    public static void main(String[] args) {
        double getGold=Math.floor(10/3);
        System.out.println(getGold);
        System.out.println((int)getGold);
    }

}
